<template>
  <div>
    <el-form label-width="80px" :inline="false" size="default">
      <el-form-item label="SPU 名称">
        <span>{{ spuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU 名称">
        <el-input size="default" clearable v-model="skuInfo.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input size="default" clearable v-model="skuInfo.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input size="default" clearable v-model="skuInfo.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          size="default"
          clearable
          type="textarea"
          v-model="skuInfo.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form label-width="80px" :inline="true" size="default">
          <el-form-item
            :label="attr.attrName"
            v-for="attr in attrList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" clearable v-model="attr.selectData">
              <el-option
                v-for="item in attr.attrValueList"
                :key="item.id"
                :label="item.valueName"
                :value="`${attr.id}:${item.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="80px" :inline="true" size="default">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="saleAttr in saleAttrList"
            :key="saleAttr.id"
          >
            <el-select
              placeholder="请选择"
              clearable
              v-model="saleAttr.selectData"
            >
              <el-option
                v-for="item in saleAttr.spuSaleAttrValueList"
                :key="item.id"
                :label="item.saleAttrValueName"
                :value="`${saleAttr.id}:${item.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table
          border
          stripe
          :data="spuImageList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" width="100" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="primary"
                size="small"
                v-if="row.isDefault === '0'"
                @click="changeDefault(row)"
                >设为默认</el-button
              >
              <el-tag type="primary" size="small" v-else>默认图片</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="emit('changeType', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "SkuForm",
});
</script>

<script setup lang="ts">
import { reqAttrInfoList, type attrListType } from "@/api/attr";
import type { skuInfoItemDetailType } from "@/api/sku";
import { reqSaleAttrSelf, reqSpuImageList } from "@/api/spu";
import type {
  spuItemType,
  saleAttrListType,
  spuImgItemType,
  spuImgListType,
} from "@/api/spu";
import { storeToRefs } from "pinia";
import useCategoryStore from "@/stores/category";
import { reqAddSku } from "@/api/sku";
const categoryStore = useCategoryStore();
//拿到当前新增sku的所在的spu的信息
const props = defineProps<{
  spuInfo: spuItemType;
}>();
//接收切换type的自定义事件
const emit = defineEmits<{
  (event: "changeType", type: number, row?: spuItemType): void;
}>();

//拿到category的所有的id
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

//初始化数据收集平台属性列表,销售属性列表,spu图片列表
const attrList = ref<attrListType>([]);
const saleAttrList = ref<saleAttrListType>([]);
const spuImageList = ref<spuImgListType>([]);

const initData = async () => {
  const p1 = reqAttrInfoList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const p2 = reqSaleAttrSelf(props.spuInfo.id as number);
  const p3 = reqSpuImageList(props.spuInfo.id as number);

  try {
    const result = await Promise.all([p1, p2, p3]);
    attrList.value = result[0];
    attrList.value.forEach((item) => {
      item.selectData = "";
    });
    saleAttrList.value = result[1];
    saleAttrList.value.forEach((item) => {
      item.selectData = "";
    });
    spuImageList.value = result[2];
    spuImageList.value.forEach((item) => {
      item.isDefault = "0";
    });
  } catch (e: any) {
    ElMessage.error(e.message);
  }
};

//初始化请求数据
onMounted(() => {
  initData();
});

//初始化收集数据
const skuInfo = ref<skuInfoItemDetailType>({
  // id?: number,
  spuId: props.spuInfo.id as number, //所在的spuId
  price: 0, //当前sku的价格
  skuName: "", //当前sku的名称
  skuDesc: "", //当前sku的描述
  weight: "", //当前sku的重量
  tmId: props.spuInfo.tmId, //当前sku所在的品牌id
  category3Id: props.spuInfo.category3Id, //当前sku所在的三级分类的id
  skuDefaultImg: "", //当前sku的默认的图片
  isSale: 1, //当前sku是否上架
  // createTime: string, //当前sku的创建时间
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});

//收集图片数据时候的数据类型
interface selectionType {
  id: number;
  imgName: string;
  imgUrl: string;
  spuId: number;
  isDefault: string;
}
//收集图片数据
const skuImgList = ref<selectionType[]>([]);
//收集图片的事件函数
const handleSelectionChange = (selection: selectionType[]) => {
  console.log(selection);
  skuImgList.value = selection;
};

//切换默认图片
const changeDefault = (row: spuImgItemType) => {
  //先把所有的图片的isDefault都设置为0
  spuImageList.value.forEach((item) => {
    item.isDefault = "0";
  });
  row.isDefault = "1";

  //把当前点击的默认图片的地址 收集到skuInfo中
  skuInfo.value.skuDefaultImg = row.imgUrl;
};

const save = async () => {
  //整理图片参数(我们之前把参数收集到skuImgList)
  skuInfo.value.skuImageList = skuImgList.value.map((item) => {
    return {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id,
      isDefault: item.isDefault,
    };
  });

  //整理平台属性(只需要收集attrid和valueid即可，其他属性都是可选)
  attrList.value.forEach((item) => {
    if (!item.selectData) return;
    const [attrId, valueId] = item.selectData.split(":");
    skuInfo.value.skuAttrValueList.push({
      attrId: +attrId,
      valueId: +valueId,
    });
  });

  //整理销售属性(只需要收集attrid和valueid即可，其他属性都是可选)
  saleAttrList.value.forEach((item) => {
    if (!item.selectData) return;
    const [saleAttrId, saleAttrValueId] = item.selectData.split(":");
    skuInfo.value.skuSaleAttrValueList.push({
      saleAttrId: +saleAttrId,
      saleAttrValueId: +saleAttrValueId,
    });
  });

  try {
    await reqAddSku(skuInfo.value);
    ElMessage.success("添加sku成功");
    emit("changeType", 0);
  } catch (e: any) {
    ElMessage.error(e.message);
  }
};
</script>

<style scoped></style>
